﻿namespace MAdesantis
{
    using System;
    using System.Text;
    using System.Activities;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using Microsoft.SharePoint.Workflow;
    using Microsoft.SharePoint.WorkflowActions;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.Collections.ObjectModel;

    public sealed class Util
    {
        public static String GetFileNameAndExt(string URL)
        {
            String result = string.Empty;

            try
            {
                if (!string.IsNullOrWhiteSpace(URL))
                {
                    String[] str = URL.Split(new Char[] { '/' });
                    result = str[str.Length - 1];
                }
            }
            catch (Exception ex)
            {
                Log.LogError("Util.GetFileNameAndExt : " + ex.Message);
            }

            return result;
        }

    }

    public sealed class InheritanceResetRole : CodeActivity//ILSPY
    {
        public InArgument<string> Site_Url { get; set; }//%1
        public InArgument<string> List_Name { get; set; }//%2

        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                string _urlDocumento = (string)context.DataContext.GetProperties()["Microsoft.SharePoint.ActivationProperties.CurrentItemUrl"].GetValue(context.DataContext);
                string _Sitio = (string)context.GetValue(this.Site_Url);
                string _Sucursal = (string)context.GetValue(this.List_Name);

                ResetRoleInheritance(_Sitio, _Sucursal, _urlDocumento);

            }
            catch (Exception ex)
            {
                Log.LogError("Activitie [Inheritance Reset Role] - ResetRoleInheritance : " + ex.Message);
            }
            finally
            {
                Log.LogInfo("Activitie [Inheritance Reset Role] - ResetRoleInheritance : Finalizo Correctamente");
            }

            return;//?
        }

        public void ResetRoleInheritance(string URLSite, string Sucursal, string UrlDocumento)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(URLSite))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {

                            site.AllowUnsafeUpdates = true;
                            web.AllowUnsafeUpdates = true;

                            SPFile file = null;
                            SPFileCollection files = web.Lists[Sucursal].RootFolder.Files;

                            string nameFile = Util.GetFileNameAndExt(UrlDocumento);

                            foreach (SPFile item in files)
                            {
                                if (item.Name == nameFile)
                                {
                                    file = item;
                                }
                            }

                            SPListItem _item = file.Item;

                            _item.ResetRoleInheritance();

                            web.AllowUnsafeUpdates = false;
                            site.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception)
            {
                throw;
            }

        }

    }

    public sealed class AssignPermissionsUsers : CodeActivity//ILSPY
    {
        public InArgument<string> UrlOfSite { get; set; }//%1
        public InArgument<string> NameDocumentLibrary { get; set; }//%2
        public InArgument<Boolean> Permissions { get; set; }//%3
        public InArgument<Collection<string>> UsersList { get; set; }//%4

        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                string _urlDocumento = (string)context.DataContext.GetProperties()["Microsoft.SharePoint.ActivationProperties.CurrentItemUrl"].GetValue(context.DataContext);
                string _UrlOfSite = (string)context.GetValue(this.UrlOfSite);
                string _NameDocumentLibrary = (string)context.GetValue(this.NameDocumentLibrary);
                bool _Permissions = (bool)context.GetValue(this.Permissions);
                Collection<string> _UsersList = (Collection<string>)context.GetValue(this.UsersList);
                
                StringBuilder sb = new StringBuilder();

                if (_UsersList.Count > 0)
                {
                    foreach (var item in _UsersList)
                    {
                        sb.Append(item + ";");
                    }
                }

                //Log.LogInfo("Este es mi ArrayList:" + sb.ToString());

                AsignarPermisos(_UrlOfSite, _NameDocumentLibrary, _Permissions, _urlDocumento, sb.ToString());

            }
            catch (Exception ex)
            {
                Log.LogError("Activitie [Assign Permissions Users] - Execute : " + ex.Message);
            }

            return;//?
        }

        public void AsignarPermisos(string URLSite, string Sucursal, bool Permisos, string UrlDocumento, string Usuarios)
        {
            using (SPSite site = new SPSite(URLSite))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true;

                    SPFile file = null;
                    string nameFile = Util.GetFileNameAndExt(UrlDocumento);
                    SPFileCollection files = web.Lists[Sucursal].RootFolder.Files;

                    foreach (SPFile item in files)
                    {
                        if (item.Name == nameFile)
                        {
                            file = item;
                        }
                    }

                    SPListItem _item = file.Item;

                    if (Permisos)
                    {
                        UpdatePermissions(_item, web, Usuarios);
                    }
                    else
                    {
                        UpdatePermissionsComple(_item, web, Usuarios);
                    }

                    web.AllowUnsafeUpdates = false;
                    site.AllowUnsafeUpdates = false;
                }
            }
        }

        public void UpdatePermissions(SPListItem itemCurrent, SPWeb webCurrent, string Usuarios)
        {
            try
            {
                String[] User = Usuarios.Split(new char[] { ';' });

                foreach (var item in User)
                {

                    itemCurrent.BreakRoleInheritance(true);

                    SPRoleDefinition roleDefinition = webCurrent.RoleDefinitions.GetByType(SPRoleType.Contributor);
                    SPUser spUser = webCurrent.EnsureUser(item.ToString());
                    SPRoleAssignment roleAssigment = new SPRoleAssignment(spUser);

                    roleAssigment.RoleDefinitionBindings.Add(roleDefinition);
                    itemCurrent.RoleAssignments.Add(roleAssigment);

                }
            }
            catch (Exception ex)
            {
                Log.LogError("Activitie [Assign Permissions Users] - UpdatePermissions : " + ex.Message);
            }

        }

        public void UpdatePermissionsComple(SPListItem itemCurrent, SPWeb webCurrent, string Usuarios)
        {
            try
            {
                String[] User = Usuarios.Split(new char[] { ';' });

                foreach (var item in User)
                {
                    itemCurrent.BreakRoleInheritance(true);

                    SPUser spUser = webCurrent.EnsureUser(item.ToString());

                    itemCurrent.RoleAssignments.Remove(spUser);

                }
            }
            catch (Exception ex)
            {
                Log.LogError("Activitie [Assign Permissions Users] - UpdatePermissionsComple : " + ex.Message);
            }

        }

    }

}
